#!groovy
// kafka create piplines
pipeline{
    agent{
        label "slave"
    }
    parameters{
        string(name: 'Topics Name', defaultValue: '', description: '请输入你要创建的topics 名字'),
        //string(name: 'Topics Name', defaultValue: '1', description: '请输入你要创建的topics 名字')
        choice(name: 'ENVIRONMENT', choices: ['dev'], description: '选择环境信息')
    }

    environment{
        dev = "nonlive-core-hsm-proxy-1"
    }

    stages{
        stage("Set Config"){
            steps{
                echo "========set config========"
                wrap([$class: 'BuildUser']) {
                    buildName "${currentBuild.number}-${params.ENVIRONMENT}-${BUILD_USER}"
                    buildDescription "branch: ${GIT_BRANCH}\ncommit: ${GIT_COMMIT}\n"
                }
            }
        }

        stage("Git Clone"){
            steps{
                echo "========fetch from repo========"
                checkout(
                    [
                        $class: 'GitSCM',
                        branches: [[
                            name: getFinalBranch()
                        ]],
                        doGenerateSubmoduleConfigurations: false,
                        extensions: [],
                        gitTool: 'Default',
                        userRemoteConfigs: [[
                            url: scm.getUserRemoteConfigs()[0].getUrl(),
                            credentialsId: scm.getUserRemoteConfigs()[0].getCredentialsId()
                        ]],
                    ]
                )
            }
        }

    stage('Build'){
        steps{
              withMaven(
                    // Maven installation declared in the Jenkins "Global Tool Configuration"
                    maven: 'maven3.6.3', // (1)
                    // Use `$WORKSPACE/.repository` for local repository folder to avoid shared repositories
                    // mavenLocalRepo: '.repository', // (2)
                    // Maven settings.xml file defined with the Jenkins Config File Provider Plugin
                    // We recommend to define Maven settings.xml globally at the folder level using
                    // navigating to the folder configuration in the section "Pipeline Maven Configuration / Override global Maven configuration"
                    // or globally to the entire master navigating to  "Manage Jenkins / Global Tools Configuration"
                    mavenSettingsConfig: 'maven-settings' // (3)
                ) {
                    sh "mvn clean package -Dmaven.test.skip=true -Denv=${params.ENVIRONMENT}"
            }
        }
    }

        stage("Deploy"){
            steps{
                echo "========deploy to the target server========"
                script {
                    def config = ""

                    switch(params.ENVIRONMENT){
                        case "dev1":
                            config = "${ dev1 }"
                            break
                        case "uat1":
                            config = "${ uat1 }"
                            break
                        case "sit1":
                            config = "${ sit1 }"
                            break
                        case "sit2":
                            config = "${ sit2 }"
                            break
                        case "live":
                            config = "${ live }"
                            break
                        case "dr":
                            config = "${ dr }"
                            break
                        default:
                            config = "${ dev1 }"
                            break
                    }

                    config.tokenize(',').each {
                        deploy("${ it }")
                    }
                }
            }
        }
    }
}

// 处理函数

def getFinalBranch() {
    // 反回git分支信息
    def tag = ""
    if (params.TAG_RELEASE){
        tag = params.TAG
    }else {
        tag = params.BRANCH
    }
    return tag
}

def transfer2SingleDir(String tag) {
    String tmp = tag.replaceAll("origin/", "")
    return tmp.replaceAll("/", "-")
}

def deploy(String ServerName) {
    def tag = getFinalBranch()
    def finalTag = transfer2SingleDir(tag)
    sshPublisher(
        publishers: [
            sshPublisherDesc(
                configName: "${ ServerName }",
                verbose: true,
                transfers: [
                    sshTransfer(
                        cleanRemote: true,
                        excludes: '',
                        execCommand: "sudo echo -e '[program:${APP_NAME}-${params.ENVIRONMENT}] \ncommand=/bin/bash ${params.ENVIRONMENT}/${ APP_NAME }/scripts/stop.sh ${params.ENVIRONMENT} \ncommand=/bin/bash ${params.ENVIRONMENT}/${ APP_NAME }/scripts/start.sh ${params.ENVIRONMENT} \nautostart=true \nautorestart=true \nuser=deployop \nstartsecs=10 \nkillasgroup=true \nstopasgroup=true \nredirect_stderr=true \nstdout_logfile=${APP_PATH}/log/log.log' > /etc/supervisor/conf.d/${APP_NAME}-${params.ENVIRONMENT}.conf;unzip -o ${APP_PATH}.zip -d /home/deployop/${params.ENVIRONMENT}/${ APP_NAME }/target  && chmod +x ${params.ENVIRONMENT}/${ APP_NAME }/scripts/*.sh;rm ${APP_PATH}/log/log.log;mkdir -p ${APP_PATH}/log;supervisorctl update;supervisorctl restart ${APP_NAME}-${params.ENVIRONMENT}",
                        execTimeout: 120000,
                        flatten: false,
                        makeEmptyDirs: false,
                        noDefaultExcludes: false,
                        patternSeparator: '[, ]+',
                        remoteDirectory: "${params.ENVIRONMENT}/${ APP_NAME }/",
                        remoteDirectorySDF: false,
                        removePrefix: '', 
                        sourceFiles: '**/*'
                       
                    )
                ],
            )
        ]
    )
}
